<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\ApiController;
use Illuminate\Support\Facades\Auth;
use App\Http\Resources\Admin\Product as ProductResource;
use App\Http\Resources\Admin\ProductCollection;
use App\Models\Manager;
use App\Models\Product;
use App\Models\Shop;
use Validator;
use Storage;

class ProductController extends ApiController
{
    /**
     * 获取商品列表
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $limit = $request->input('size', 15);
        $keyword = $request->input('keyword');
        $status = $request->input('status');

        $orm = Product::orderBy('id', 'DESC')->with(['shop' => function($query) {
            $query->select(['id', 'name']);
        }]);

        if ($keyword) {
            $shop = Shop::where('name', 'like', "%{$keyword}%")->first();
            $shop && $orm->where('shop_id', $shop->id);
        }

        if ($request->filled('status')) {
            $orm->where('status', $request->input('status'));
        }

        return new ProductCollection($orm->paginate($limit));
    }

    /**
     * 添加商品
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $messages = [
            'name.required' => '商品名称不能为空',
            'cover_image.required' => '商品封面不能为空',
            'price.required' => '商品价格不能为空'
        ];

        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'cover_image' => 'required',
            'price' => 'required'
        ], $messages);

        if ($validator->fails()) {
            return $this->failed($validator->errors()->first());
        }

        // 处理商品图片组
        $picGroup = $request->input('pic_group', []);
        $prodPics = [];
        if($picGroup){
            foreach ($picGroup as $pic) {
                array_push($prodPics, $pic['value']);
            }
        }

        // 处理商品封面图片
        $coverImage = $request->input('cover_image', '');
        if(!$coverImage){
            // 没有上传封面图片的时候从图片组里面获取第一张做封面图片
            $coverImage = $prodPics ? $prodPics[0] : '';
        }else {
            $coverImage = $coverImage['value'];
        }

        $product = new Product();
        $product->store_id = 0; // 自营店store_id为0
        $product->name = $request->input('name');
        $product->price = number_format($request->input('price'), 2, '.', '');
        $product->unit = $request->input('unit');
        $product->info = $request->input('info');
        $product->description = $request->input('desc');
        $product->cover_image = $coverImage;
        $product->pic_group = json_encode($prodPics); // 图片组存为json格式数据
        $product->spec = $request->input('spec'); // 规格
        $product->logistics_mode = json_encode($request->input('logistics_mode')); // 支持的物流方式
        $product->address = $request->input('address');
        $product->cate_id = $request->input('cate_id');
        $product->status = 1;
        $product->save();

        if(!$product){
            return $this->failed('商品创建失败');
        }else {
            return $this->message('商品创建成功');
        }
    }

    /**
     * 获取指定货品信息
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $product = Product::where('id', $id)->with(['shop' => function($query) {
            $query->select(['id', 'name']);
        }])->first();
        
        if(!$product){
            return $this->failed('货品不存在');
        } 

        return $this->success($product);
    }

    /**
     * 更新商品
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $messages = [
            'name.required' => '商品名称不能为空',
            'cover_image.required' => '商品封面不能为空',
            'price.required' => '商品价格不能为空'
        ];

        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'cover_image' => 'required',
            'price' => 'required'
        ], $messages);

        if ($validator->fails()) {
            return $this->failed($validator->errors()->first());
        }

        // 处理商品图片组
        $picGroup = $request->input('pic_group', []);
        $prodPics = [];
        if($picGroup){
            foreach ($picGroup as $pic) {
                array_push($prodPics, $pic['value']);
            }
        }

        // 处理商品封面图片
        $coverImage = $request->input('cover_image', '');
        if(!$coverImage){
            // 没有上传封面图片的时候从图片组里面获取第一张做封面图片
            $coverImage = $prodPics ? $prodPics[0] : '';
        }else {
            $coverImage = $coverImage['value'];
        }

        $product = Product::find($id);
        if(!$product){
            return $this->failed('商品更新失败');
        }
        $product->store_id = 0; // 自营店store_id为0
        $product->name = $request->input('name');
        $product->price = number_format($request->input('price'), 2, '.', '');
        $product->unit = $request->input('unit');
        $product->info = $request->input('info');
        $product->description = $request->input('desc');
        $product->cover_image = $coverImage;
        $product->pic_group = json_encode($prodPics); // 图片组存为json格式数据
        $product->spec = $request->input('spec'); // 规格
        $product->logistics_mode = json_encode($request->input('logistics_mode')); // 支持的物流方式
        $product->address = $request->input('address');
        $product->cate_id = $request->input('cate_id');
        $product->status = 1;
        $product->save();

        if(!$product){
            return $this->failed('商品更新失败');
        }else {
            return $this->message('商品更新成功');
        }

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    /**
     * 设置首页推荐
     *
     * @return void
     */
    public function recommend(Request $request)
    {
        $ids = $request->input('ids');
        $isCancel = $request->input('cancel');
        $rcmd = $isCancel == 1 ? 0 : 1;

        if ($ids && is_array($ids) && count($ids) > 0) {
            $products = Product::whereIn('id', $ids)->get();
            foreach($products as $prod) {
                $prod->rcmd = $rcmd;
                $prod->save();
            }
            return $this->message('设置成功');
        } else {
            return $this->failed('请选择货品');
        }
    }


    /**
     * 文件上传
     */
    public function uploadpic(Request $request)
    {
        $user = Auth::guard('manager')->user();
        $filename = 'cover-img';
        $filepath = storage_path('app/public/uploads/images');
        $errormsg = '';

        //1.首先检查文件是否存在
        if (!$request->hasFile($filename)){ 
            return $this->failed('图片存储失败');
        }
        // 2.获取文件
        $file = $request->file($filename);
        if($file) {
            //4图片后缀是否正确
            $extension = $file->guessExtension();
            if(!in_array(strtolower($extension),['jpeg','jpg','gif','gpeg','png'])){ 
                return $errormsg = '图片类型不正确';
            }
            //4.将文件取一个新的名字
            $newName = time() . uniqid() . '_' . $user->id . '.' . $extension;
            //5.移动文件,并修改名字

            $img = \Image::make($file)->resize(280, null, function ($constraint) {
                $constraint->aspectRatio();
            })->save($filepath.'/'.$newName);

            if($img) {
                return $this->success(['name' => $newName, 'path' => config('app.url').'/storage/uploads/images/'.$newName]);
            }else {
                return $this->faild('图片存储失败');
            }

        }else {
            return $this->faild('没有文件上传');
        }
    }
}
